import 'package:flutter/material.dart';
import 'dart:ui';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter/cupertino.dart';
import 'package:my_flutter/home/webview_page.dart';
import '/other_page.dart';
import '/splash_page.dart';
import 'package:my_flutter/util/handle_error_utils.dart';
import 'package:oktoast/oktoast.dart';
import 'package:url_strategy/url_strategy.dart';
import 'package:sp_util/sp_util.dart';
import 'package:flutter/services.dart';
import 'package:my_flutter/util/log_utils.dart';
import 'package:provider/provider.dart';
import 'package:my_flutter/setting/provider/locale_provider.dart';
import 'package:my_flutter/setting/provider/theme_provider.dart';
import 'package:my_flutter/routers/not_found_page.dart';
import 'package:my_flutter/routers/routers.dart';

import 'package:my_flutter/login/page/login_page.dart';
import 'package:my_flutter/login/page/register_page.dart';
import 'package:my_flutter/login/page/reset_password_page.dart';
import 'package:my_flutter/login/page/sms_login_page.dart';
import 'package:my_flutter/login/page/update_password_page.dart';

import 'package:my_flutter/net/net.dart';
import 'package:dio/dio.dart';
import 'package:my_flutter/net/intercept.dart';
import 'package:my_flutter/res/constant.dart';

void main() {
  ///添加全局生命周期监听类
  PageVisibilityBinding.instance
      .addGlobalObserver(AppGlobalPageVisibilityObserver());
  ///这里的CustomFlutterBinding调用务必不可缺少，用于控制Boost状态的resume和pause
  CustomFlutterBinding();

  /// 确保初始化完成
  WidgetsFlutterBinding.ensureInitialized();

  /// 去除URL中的“#”(hash)，仅针对Web。默认为setHashUrlStrategy
  /// 注意本地部署和远程部署时`web/index.html`中的base标签，https://github.com/flutter/flutter/issues/69760
  setPathUrlStrategy();

  /// sp初始化
  SpUtil.getInstance();//为什么不用await??

  /// 异常处理
  handleError(runApp(MyApp2()));

  /// 隐藏状态栏。为启动页、引导页设置。完成后修改回显示状态栏。
  SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.bottom]);
}

class MyApp2 extends StatefulWidget {
  MyApp2({Key? key}):super(key: key){
    Log.init();///初始化log
    initDio();///初始化网络
    // Routes.initRoutes(); ///初始化路由表
    // initQuickActions();///初始化3DTouch设置
  }

  void initDio(){///初始化网络
    final List<Interceptor> interceptors = <Interceptor>[];

    ///统一添加身份验证请求头
    interceptors.add(AuthInterceptor());

    ///刷新Token
    // interceptors.add(TokenInterceptor());

    ///打印Log(生产模式去除)
    if(!Constant.inProduction){
      interceptors.add(LoggingInterceptor());
    }

    /// 适配数据(根据自己的数据结构，可自行选择添加)
    interceptors.add(AdapterInterceptor());
    configDio(
      baseUrl: 'https://uagent.98809.com/',
      interceptors: interceptors,
    );
  }

  // void initQuickActions(){
  //   if(Device.isMobile){
  //     const QuickActions quickActions = QuickActions();
  //     // Android每次是重新启动activity，所以放在了splash_page处理。
  //     // 总体来说使用不方便，这种动态的方式在安卓中局限性高。这里仅做练习使用。
  //     if(Device.isIOS){
  //       quickActions.initialize((String shortcutType) async{
  //         if(shortcutType == 'demo'){
  //           navigatorKey.currentState?.push<dynamic>(MaterialPageRoute<dynamic>(
  //             builder: (BuildContext context) => const DemoPage(),
  //           ));
  //         }
  //       });
  //     }
  //
  //     quickActions.setShortcutItems(<ShortcutItem>[
  //       const ShortcutItem(
  //           type: 'demo',
  //           localizedTitle: 'Demo',
  //           icon: 'flutter_dash_black'
  //       ),
  //     ]);
  //   }
  // }

  @override
  _MyAppState2 createState() => _MyAppState2();
}

class _MyAppState2 extends State<MyApp2> {
  /// 由于很多同学说没有跳转动画，这里是因为之前exmaple里面用的是 [PageRouteBuilder]，
  /// 其实这里是可以自定义的，和Boost没太多关系，比如我想用类似iOS平台的动画，
  /// 那么只需要像下面这样写成 [CupertinoPageRoute] 即可
  /// (这里全写成[MaterialPageRoute]也行，这里只不过用[CupertinoPageRoute]举例子)
  ///
  /// 注意，如果需要push的时候，两个页面都需要动的话，
  /// （就是像iOS native那样，在push的时候，前面一个页面也会向左推一段距离）
  /// 那么前后两个页面都必须是遵循CupertinoRouteTransitionMixin的路由
  /// 简单来说，就两个页面都是CupertinoPageRoute就好
  /// 如果用MaterialPageRoute的话同理
  static Map<String, FlutterBoostRouteFactory> routerMap = {
    'login': (settings, uniqueId) {
      print(settings);
      print(uniqueId);
      return PageRouteBuilder<dynamic>(
          settings: settings,
          pageBuilder: (_, __, ___) => LoginPage());
    },
    'register': (settings, uniqueId) {
      return PageRouteBuilder<dynamic>(
          settings: settings,
          pageBuilder: (_, __, ___) => RegisterPage());
    },
    'smsLogin': ( settings,  uniqueId) {
      return PageRouteBuilder<dynamic>(
          settings: settings,
          pageBuilder: (_, __, ___) => SMSLoginPage());
    },
    'resetPassword': (settings, uniqueId) {
      return PageRouteBuilder<dynamic>(
          settings: settings,
          pageBuilder: (_, __, ___) => ResetPasswordPage());
    },
    'updatePassword': (settings, uniqueId) {
      return PageRouteBuilder<dynamic>(
          settings: settings,
          pageBuilder: (_, __, ___) => UpdatePasswordPage());
    },
    'webview': (settings, uniqueId) {
      Map params = (settings.arguments ?? {} ) as Map ;
      // print('webview+settings: ${settings}');
      print('webview+params:${params}');
      return PageRouteBuilder<dynamic>(
          settings: settings,
          pageBuilder: (_, __, ___) => WebViewPage(title: params['title'], url: params['url']));
    },
  };


  Route<dynamic>? routeFactory(RouteSettings settings, String? uniqueId) {
    FlutterBoostRouteFactory? func = routerMap[settings.name];
    if (func == null) {
      return null;
    }
    // print('routeFactory+settings: ${settings}');
    return func(settings, uniqueId);
  }

  @override
  void initState() {
    super.initState();
  }

  Widget appBuilder(Widget home) {
    return MaterialApp(
      home: home,
      debugShowCheckedModeBanner: true,
      ///必须加上builder参数，否则showDialog等会出问题
      builder: (_, __) {
        return home;
      },
    );
  }

  Widget _buildFlutterBoostApp1(settings, uniqueId) {
    return FlutterBoostApp(
      routeFactory,
      appBuilder: appBuilder,
      initialRoute: "login",
    );
  }

  @override
  Widget build(BuildContext context) {

    final Widget _buildFlutterBoostApp = FlutterBoostApp(
      routeFactory,
      appBuilder: appBuilder,
      initialRoute: "login",
    );

    ///Toast 配置:OKToast需要包裸一个MaterialApp，后期才不需要穿context
    return OKToast(
        child: _buildFlutterBoostApp,
        backgroundColor: Colors.black54,
        textPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
        radius: 20.0,
        position: ToastPosition.bottom
    );

  }
}

//*******provider*********//
class MyApp1 extends StatelessWidget {
  MyApp1({Key? key,this.home,this.theme}):super(key: key){
    Log.init();///初始化log
    // initDio();///初始化网络
    Routes.initRoutes(); ///初始化路由表
    // initQuickActions();///初始化3DTouch设置
  }

  final Widget? home;
  final ThemeData? theme;
  static GlobalKey<NavigatorState> navigatorKey = GlobalKey();

  // void initDio(){///初始化网络
  //   final List<Interceptor> interceptors = <Interceptor>[];
  //
  //   ///统一添加身份验证请求头
  //   interceptors.add(AuthInterceptor());
  //
  //   ///刷新Token
  //   interceptors.add(TokenInterceptor());
  //
  //   ///打印Log(生产模式去除)
  //   if(!Constant.inProduction){
  //     interceptors.add(LoggingInterceptor());
  //   }
  //
  //   /// 适配数据(根据自己的数据结构，可自行选择添加)
  //   interceptors.add(AdapterInterceptor());
  //   configDio(
  //     baseUrl: 'https://api.github.com/',
  //     interceptors: interceptors,
  //   );
  // }

  // void initQuickActions(){
  //   if(Device.isMobile){
  //     const QuickActions quickActions = QuickActions();
  //     // Android每次是重新启动activity，所以放在了splash_page处理。
  //     // 总体来说使用不方便，这种动态的方式在安卓中局限性高。这里仅做练习使用。
  //     if(Device.isIOS){
  //       quickActions.initialize((String shortcutType) async{
  //         if(shortcutType == 'demo'){
  //           navigatorKey.currentState?.push<dynamic>(MaterialPageRoute<dynamic>(
  //             builder: (BuildContext context) => const DemoPage(),
  //           ));
  //         }
  //       });
  //     }
  //
  //     quickActions.setShortcutItems(<ShortcutItem>[
  //       const ShortcutItem(
  //           type: 'demo',
  //           localizedTitle: 'Demo',
  //           icon: 'flutter_dash_black'
  //       ),
  //     ]);
  //   }
  // }

  @override
  Widget build(BuildContext context) {

    final Widget app = MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => ThemeProvider()),
        ChangeNotifierProvider(create: (_) => LocaleProvider())
      ],
      child: Consumer2<ThemeProvider, LocaleProvider>(
        builder: (_, ThemeProvider provider, LocaleProvider localeProvider, __) {
          return _buildMaterialApp(provider, localeProvider);
        },
      ),
    );

    ///Toast 配置:OKToast需要包裸一个MaterialApp，后期才不需要穿context
    return OKToast(
        child: app,
        backgroundColor: Colors.black54,
        textPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
        radius: 20.0,
        position: ToastPosition.bottom
    );
  }

  Widget _buildMaterialApp(ThemeProvider provider, LocaleProvider localeProvider) {
    return MaterialApp(
      title: 'Flutter Deer',
      // showPerformanceOverlay: true, //显示性能标签
      // debugShowCheckedModeBanner: false, // 去除右上角debug的标签
      // checkerboardRasterCacheImages: true,
      // showSemanticsDebugger: true, // 显示语义视图
      // checkerboardOffscreenLayers: true, // 检查离屏渲染
      theme: theme ?? provider.getTheme(),
      darkTheme: provider.getTheme(isDarkMode: true),
      themeMode: provider.getThemeMode(),
      home: home ?? LoginPage(),
      onGenerateRoute: Routes.router.generator,
      // localizationsDelegates: DeerLocalizations.localizationsDelegates,
      // supportedLocales: DeerLocalizations.supportedLocales,
      locale: localeProvider.locale,
      navigatorKey: navigatorKey,
      builder: (BuildContext context, Widget? child) {
        /// 仅针对安卓
        // if (Device.isAndroid) {
        //   /// 切换深色模式会触发此方法，这里设置导航栏颜色
        //   ThemeUtils.setSystemNavigationBar(provider.getThemeMode());
        // }

        /// 保证文字大小不受手机系统设置影响 https://www.kikt.top/posts/flutter/layout/dynamic-text/
        return MediaQuery(
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
          child: child!,
        );
      },

      /// 因为使用了fluro，这里设置主要针对Web
      onUnknownRoute: (_) {
        return MaterialPageRoute<void>(
          builder: (BuildContext context) => const NotFoundPage(),
        );
      },
      restorationScopeId: 'app',
    );
  }
}


//*******FlutterBoost*********//
///全局生命周期监听示例
class AppGlobalPageVisibilityObserver extends GlobalPageVisibilityObserver {
  @override
  void onPagePush(Route<dynamic> route) {
    super.onPagePush(route);
    Logger.log(
        'boost_lifecycle: AppGlobalPageVisibilityObserver.onPageCreate route:${route.settings.name}');
  }

  @override
  void onPagePop(Route<dynamic> route) {
    super.onPagePop(route);
    Logger.log(
        'boost_lifecycle: AppGlobalPageVisibilityObserver.onPageDestroy route:${route.settings.name}');
  }

  @override
  void onPageShow(Route<dynamic> route) {
    super.onPageShow(route);
    Logger.log(
        'boost_lifecycle: AppGlobalPageVisibilityObserver.onPageShow route:${route.settings.name}');
  }

  @override
  void onPageHide(Route<dynamic> route) {
    super.onPageHide(route);
    Logger.log(
        'boost_lifecycle: AppGlobalPageVisibilityObserver.onPageHide route:${route.settings.name}');
  }

  @override
  void onForeground(Route route) {
    super.onForeground(route);
    Logger.log(
        'boost_lifecycle: AppGlobalPageVisibilityObserver.onForeground route:${route.settings.name}');
  }

  @override
  void onBackground(Route<dynamic> route) {
    super.onBackground(route);
    Logger.log(
        'boost_lifecycle: AppGlobalPageVisibilityObserver.onBackground route:${route.settings.name}');
  }
}

///创建一个自定义的Binding，继承和with的关系如下，里面什么都不用写
class CustomFlutterBinding extends WidgetsFlutterBinding with BoostFlutterBinding {}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  /// 由于很多同学说没有跳转动画，这里是因为之前exmaple里面用的是 [PageRouteBuilder]，
  /// 其实这里是可以自定义的，和Boost没太多关系，比如我想用类似iOS平台的动画，
  /// 那么只需要像下面这样写成 [CupertinoPageRoute] 即可
  /// (这里全写成[MaterialPageRoute]也行，这里只不过用[CupertinoPageRoute]举例子)
  ///
  /// 注意，如果需要push的时候，两个页面都需要动的话，
  /// （就是像iOS native那样，在push的时候，前面一个页面也会向左推一段距离）
  /// 那么前后两个页面都必须是遵循CupertinoRouteTransitionMixin的路由
  /// 简单来说，就两个页面都是CupertinoPageRoute就好
  /// 如果用MaterialPageRoute的话同理
  static Map<String, FlutterBoostRouteFactory> routerMap = {
    'splash': (settings, uniqueId) {
      return PageRouteBuilder<dynamic>(
          settings: settings,
          pageBuilder: (_, __, ___) => SplashPage());
    },
    'otherPage': (settings, uniqueId) {
      return PageRouteBuilder<dynamic>(
          settings: settings,
          pageBuilder: (_, __, ___) => OtherPage(data: 'otherPage',));
    },
    'route1': ( settings,  uniqueId) {
      return PageRouteBuilder<dynamic>(
          settings: settings,
          pageBuilder: (_, __, ___) => OtherPage(data: 'route1',));
    },
    'route2': (settings, uniqueId) {
      return PageRouteBuilder<dynamic>(
          settings: settings,
          pageBuilder: (_, __, ___) => OtherPage(data: 'route2'));
      return CupertinoPageRoute(
          settings: settings,
          builder: (_) {
            Map<String, Object> map = settings.arguments as Map<String, Object>;
            String data = map['data'] as String;
            return MainPage(
              data: data,
            );
          });
    },
  };


  Route<dynamic>? routeFactory(RouteSettings settings, String? uniqueId) {
    FlutterBoostRouteFactory? func = routerMap[settings.name];
    if (func == null) {
      return null;
    }
    return func(settings, uniqueId);
  }
  @override
  void initState() {
    super.initState();
  }

  Widget appBuilder(Widget home) {
    return MaterialApp(
      home: home,
      debugShowCheckedModeBanner: true,
      ///必须加上builder参数，否则showDialog等会出问题
      builder: (_, __) {
        return home;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return FlutterBoostApp(
      routeFactory,
      appBuilder: appBuilder,
     initialRoute: "route2",
    );
  }
}

class MainPage extends StatelessWidget {
  const MainPage({this.data='',});

  final String data;

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
          child: Text('Main Page')
      ),
    );
  }
}
